<?php
/**
 * Num 记录和字符串相关的类库中的方法
 */
namespace app\common\lib;

class Str
{

    /**
     * 生成登录所需要的token
     * @param $string
     * @return string
     */
    public static function getLoginToken($string)
    {
        // 生成token
        $str = md5(uniqid(md5(microtime(true)),true)); //生成一个不会重复的字符串
        // 加密
        return sha1($str.$string);
    }

    /**
     * 随机生成颜色值
     * @return string
     */
    public static function randomColor() {
        $str = '#';
        for($i = 0 ; $i < 6 ; $i++) {
            $randNum = rand(0 , 15);
            switch ($randNum) {
                case 10: $randNum = 'A'; break;
                case 11: $randNum = 'B'; break;
                case 12: $randNum = 'C'; break;
                case 13: $randNum = 'D'; break;
                case 14: $randNum = 'E'; break;
                case 15: $randNum = 'F'; break;
            }
            $str .= $randNum;
        }
        return $str;
    }

    /**
     * HmacSHA1
     * @param $str
     * @param $key
     * @return string
     */
    public static function getSignature($str, $key) {
        $signature = "";
        if (function_exists('hash_hmac')) {
            $signature = bin2hex(hash_hmac("sha1", $str, $key, true));
        } else {
            $blocksize = 64;
            $hashfunc = 'sha1';
            if (strlen($key) > $blocksize) {
                $key = pack('H*', $hashfunc($key));
            }
            $key = str_pad($key, $blocksize, chr(0x00));
            $ipad = str_repeat(chr(0x36), $blocksize);
            $opad = str_repeat(chr(0x5c), $blocksize);
            $hmac = pack(
                'H*', $hashfunc(
                    ($key ^ $opad) . pack(
                        'H*', $hashfunc(
                            ($key ^ $ipad) . $str
                        )
                    )
                )
            );
            $signature = bin2hex($hmac);
        }
        return $signature;
    }
}
